package com.sunkyc.framework.handler;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.sunkyc.framework.system.entity.LoginRole;
import com.sunkyc.framework.system.service.LoginService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.Parenthesis;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.expression.operators.relational.ItemsList;
import net.sf.jsqlparser.schema.Column;

import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class MyDataPermissionHandler {
    @SneakyThrows(Exception.class)
    public Expression getSqlSegment(Expression where) {
        LoginService loginService = SpringUtil.getBean(LoginService.class);
        // todo--获取权限过滤相关信息
        // 获取用户id
        long currentId = StpUtil.getLoginIdAsLong();
        // 根据用户id获取用户所对应的权限
        List<LoginRole> loginRoles = loginService.queryLoginRoleByUserId(currentId);
        // 判断是否是超级管理员 是，直接返回
        if(loginService.checkAdmin(loginRoles)){
            return where;
        }
        // 根据用户获取拥有的用户列表信息
        List<Long> authUserList = loginService.getAuthUserList(loginRoles, currentId);
        ItemsList itemsList = new ExpressionList(authUserList.stream().map(LongValue::new).collect(Collectors.toList())); // 把集合转变为JSQLParser需要的元素列表
        InExpression inExpression = new InExpression(new Column("create_by"), itemsList); //  create_by IN (2, 3, 4, 5)
        Parenthesis parenthesis = new Parenthesis(inExpression);
        if (ObjectUtil.isNotNull(where)) {
            return new AndExpression(where, parenthesis);
        } else {
            return parenthesis;
        }

    }
}
